/******************************************************************
 * Created by: DO HOANG HAI                                       
 * Date of Creation: 22/Sep/2007                    
 * Date of last modification: 20/Dec/2007
 *                                                                
 * Description: Form for displaying search result
 ******************************************************************/

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Pbdms.Common;
using Pbdms.Common.DataObject;
using Pbdms.BusinessLogic.DataController;
using Pbdms.BusinessLogic.Search;


namespace Pbdms.Forms.Tools
{
    public partial class FrmBrowse : Form
    {
        //data of the form        
        private ArrayList arlMyBuddies;
        private ArrayList arlCompBuddies;
        private ArrayList arlResultList;

        //keep track of whether some information need to be updated before witch to others
        private bool bNeedSaveItemInfo = false;
        private bool bNeedSaveGrdvInfo = false;
        private int currentSelectedItemIndex = 0;
        private BusinessLogic.Network.NetworkController ntwCtrl;

        //to indicate whether the chages have been made in item info or the changes are because of 
        //moving to another item (change the item by selecting a different row)
        bool rowSelectionChanged = false;
        bool bRefreshing = false;

        #region "public properties and constructors"
        public ArrayList ArlResultList
        {
            get { return arlResultList; }
            set { arlResultList = value; }
        }

        public FrmBrowse()
        {
            InitializeComponent();
            Pbdms.Common.Global.paintBackGround(this);
            this.ntwCtrl = Program.networkCtrller;
            load();
        }

        #endregion

        #region "load form and data"

        /// <summary>
        /// load the form
        /// </summary>
        private void load()
        {
            loadCategories();
            loadMyBuddies();
            if (arlCompBuddies!=null && arlCompBuddies.Count>0)
                loadCompBuddies();
            if (arlResultList !=null && arlResultList.Count >0)
                loadResultItems();
        }

        private void loadCompBuddies()
        {
            
            ddlCompBuddy.Items.Clear();
            if (arlCompBuddies != null && arlCompBuddies.Count > 0)
            {
                sortString(arlCompBuddies);
                foreach (String str in arlCompBuddies)
                {
                    ddlCompBuddy.Items.Add(str);
                }
            }
        }

        private void sortString(ArrayList arlCompBuddies)
        {
            for (int i = 0; i <= arlCompBuddies.Count - 2; i++)
            {
                for (int j = i + 1; j <= arlCompBuddies.Count - 1; j++)
                {
                    if (((String)(arlCompBuddies[i])).CompareTo(((String)(arlCompBuddies[j]))) > 0)
                    {
                        String temp = (String)(arlCompBuddies[i]);
                        arlCompBuddies[i] = arlCompBuddies[j];
                        arlCompBuddies[j] = temp;
                    }
                }
            }
        }

        private void loadMyBuddies()
        {
            ddlBuddyName.Items.Clear();
            arlMyBuddies = BusinessLogic.DataController.BuddyController.create().getListOfBuddies();
            //add buddies to the dropdownlist
            sortBuddies(arlMyBuddies);
            foreach (Buddy bdy in arlMyBuddies)
            {
                ddlBuddyName.Items.Add(bdy.Name);
            }
        }
        private void sortBuddies(ArrayList arl)
        {
            for (int i = 0; i <= arl.Count-2; i++)
            {
                for (int j = i+1; j <= arl.Count - 1; j++)
                {
                    if (((Buddy)(arl[i])).Name.CompareTo(((Buddy)(arl[j])).Name)>0)
                    {
                        Buddy temp = (Buddy)(arl[i]);
                        arl[i] = arl[j];
                        arl[j] = temp;
                    }
                }
            }
        }

        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            if (bNeedSaveGrdvInfo == true || bNeedSaveItemInfo == true)
            {
                int returnValue = Common.Global.showMsgThreeButtons("Would you like to save your changes before close the windows?", 'I');
                if (returnValue == Common.GUI.MsgBoxThreeButtons.DIALOG_RESULT_YES) //button Yes is clicked ->save the information
                {
                    if (bNeedSaveGrdvInfo) saveGrdvInfo();
                    if (bNeedSaveItemInfo) saveItemInfo();
                    base.OnFormClosing(e);
                }
                if (returnValue == Common.GUI.MsgBoxThreeButtons.DIALOG_RESULT_NO)
                {
                    base.OnFormClosing(e);
                }
                if (returnValue == Common.GUI.MsgBoxThreeButtons.DIALOG_RESULT_CANCEL)
                {
                    e.Cancel = true;
                }

            }
        }

        /// <summary>
        /// load categories from the database
        /// </summary>
        private void loadCategories()
        {
            ArrayList arl;
            arl = CategoryController.create().getListOfCategories();
            ddlCategory.Items.Clear();
            for (int i = 0; i < arl.Count; i++)
            {
                ddlCategory.Items.Add(arl[i].ToString());
            }
            
        }

        /// <summary>
        /// load information of a particular result item
        /// </summary>
        /// <param name="item"></param>
        private void loadResultItemInfo(Common.DataObject.ResultItem item)
        {
            //first time load, no need to check for save changes
            bNeedSaveItemInfo = false;
            if (item == null)
            {
                //if there is no item in the result list, simply disable controls of this section
                
                clearItemInfo();
                enableItemInfo(false);
                setVisibility(true);
                //no need to check for save changes
                //bNeedSaveItemInfo = false;
                return;
            }
            //otherwise, display the detail
            
            ddlCategory.SelectedIndex = Common.Global.getDdlItemByStringValue(ddlCategory, item.ItemObj.Category);
            
            tbSummary.Text = item.CommentObj.Summary;
            tbPros.Text = item.CommentObj.Pros;
            tbCons.Text = item.CommentObj.Cons;
            mtbRating.Text = item.CommentObj.Rating.ToString();
            //tags
            String newTag = "";
            
            if (item.CommentObj.Tags != null)
            {
                foreach (object sTag in item.CommentObj.Tags)
                {
                     newTag = newTag + ((String)sTag).Trim() + ", ";
                }
                newTag = newTag.Substring(0, newTag.Length - 2);
            }
            tbTag.Text = newTag;
            //existence of the file
            if (item.FileInfoObj.Existence)
                lblFileExistence.Text = "Yes";
            else
                lblFileExistence.Text = "No";
            lblFileSize.Text = item.FileInfoObj.Size.ToString();

            //differences between the case for local item and item on the network
            if (item.SourceOfItem == ResultItem.ITEM_SOURCE_LOCAL)
            {
                tbReviewFile.Text = item.CommentObj.ReviewFile;
                //enable editing capability
                enableItemInfo(true);
                //visibility
                setVisibility(true);

                //values:
                if (item.FileInfoObj.Location.Contains("http"))
                {
                    tbFileLocation.Text = item.FileInfoObj.Location + "/" + item.FileInfoObj.FileName;
                }
                else
                {
                    tbFileLocation.Text = item.FileInfoObj.Location + "\\" + item.FileInfoObj.FileName;
                }                
                chkBShare.Checked = !item.ItemObj.BPrivate; 

                //add event handlers - event handlers will be enabled to change 
                //the item's data, so it is only for local resource 
                //this.grdvItem.CellClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.grdvItem_CellContentClick);
                
                this.openFileDlg.FileOk += new CancelEventHandler(openFileDlg_FileOk);
                openFileDlgReviewFile.FileOk += new CancelEventHandler(openFileDlgReviewFile_FileOk);
                this.mtbRating.TextChanged += new EventHandler(mtbRating_TextChanged);
                this.grdvItem.CellValueChanged += new DataGridViewCellEventHandler(grdvItem_CellValueChanged);                
                this.grdvItem.SelectionChanged += new EventHandler(grdvItem_SelectionChanged);
                this.chkBShare.CheckedChanged += new System.EventHandler(this.chkBShare_CheckedChanged);
                this.tbSummary.TextChanged += new System.EventHandler(this.tbSummary_TextChanged);
                this.tbFileLocation.TextChanged += new System.EventHandler(this.tbFileLocation_TextChanged);
                this.ddlCategory.SelectedIndexChanged += new System.EventHandler(this.ddlCategory_SelectedIndexChanged);
                this.tbTag.TextChanged += new System.EventHandler(this.tbTag_TextChanged);                
                this.tbPros.TextChanged += new System.EventHandler(this.tbPros_TextChanged);
                this.tbCons.TextChanged += new System.EventHandler(this.tbCons_TextChanged);
                this.tbReviewFile.TextChanged += new EventHandler(tbReviewFile_TextChanged);
            }
            else //source of item is in the network.
            {
                //disable editing capability
                enableItemInfo(false);
                setVisibility(false);
                if (item.CommentObj.ReviewFile.Contains("http"))
                {
                    lblReviewFile.Text = item.CommentObj.ReviewFile;
                }
                else
                {
                    lblReviewFile.Text = item.FileInfoObj.Location + "\\" + item.CommentObj.ReviewFile;
                }
                //if the file is located in internet (
                if (item.FileInfoObj.Location.Contains("http"))
                {
                    lblIPAddress.Text = item.FileInfoObj.Location + "/" + item.FileInfoObj.FileName;
                }
                else //otherwise, it should be on the remote computer -> display the ip address
                {                     
                    lblIPAddress.Text = item.FileInfoObj.Location +"\\"+ item.FileInfoObj.FileName;
                }
                this.grdvItem.CellValueChanged += new DataGridViewCellEventHandler(grdvItem_CellValueChanged);
                this.grdvItem.SelectionChanged += new EventHandler(grdvItem_SelectionChanged);
            }
        }

        void tbReviewFile_TextChanged(object sender, EventArgs e)
        {
            if (!rowSelectionChanged && !bRefreshing)
                bNeedSaveItemInfo = true;            
        }
           
        /// <summary>
        /// happens when the item in the list is changed (moving to another row in the gridview)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void grdvItem_SelectionChanged(object sender, EventArgs e)
        {
            if (!bRefreshing)
                rowSelectionChanged = true;
            else
                rowSelectionChanged = false;
            if (grdvItem.SelectedRows.Count != 0)
            {
                //detect whether user selects new item
                int selectedIndex = int.Parse(grdvItem.SelectedRows[0].Cells[0].Value.ToString()) -1;
                if (currentSelectedItemIndex != selectedIndex)
                {
                    //check to see if need to update changes in detailed information of the item
                    if (bNeedSaveItemInfo)
                    {
                        int returnValue = Common.Global.showMsgTwoButtons("Would you like to update your " +
                                    "changes before switch to new item?", Common.GUI.MsgBoxTwoButtons.YES_NO, 'I');
                        if (returnValue == 1) //only if the button Yes is clicked ->save the information
                        {
                            saveItemInfo();
                        }
                    }
                    //load new item information
                    
                    loadResultItemInfo((ResultItem)arlResultList[selectedIndex]);
                    currentSelectedItemIndex = selectedIndex;
                }
            }
            rowSelectionChanged = false;
            
        }

        /// <summary>
        /// set the visisbility of controls based on the location of the item
        /// </summary>
        /// <param name="isLocal">true if the item is on local,  false otherwise</param>
        private void setVisibility(bool isLocal)
        {
            tbFileLocation.Visible = isLocal;
            lblIPAddress.Visible = !isLocal;
            tbReviewFile.Visible = isLocal;
            lblReviewFile.Visible = !isLocal;
            chkBCopy.Visible = isLocal;
            lblNetwork.Visible = isLocal;
            btnBrowseFile.Visible = isLocal;
            btnReviewFileBrowser.Visible = isLocal;
            btnRunFileDoc.Visible = isLocal;
            btnRunFileReview.Visible = isLocal;
            if (isLocal)
                btnUpdateInfo.Text = "Update Information";
            else
                btnUpdateInfo.Text = "Copy to library";       
        }

        /// <summary>
        /// enable or disable controls of the Item information area
        /// </summary>
        /// <param name="enable"></param>
        private void enableItemInfo(bool enable)
        {
            ddlCategory.Enabled = enable;
            chkBShare.Enabled = enable;
            tbSummary.ReadOnly  = !enable;
            tbPros.ReadOnly = !enable;
            tbCons.ReadOnly  = !enable;
            mtbRating.ReadOnly = !enable;
            tbTag.ReadOnly  = !enable;
            btnBrowseFile.Enabled = enable;
            btnReviewFileBrowser.Enabled = enable;
            chkBCopy.Enabled = enable;
            tbFileLocation.ReadOnly = !enable;
            tbReviewFile.ReadOnly = !enable;
            chkBCopy.Checked = false;
        }

        /// <summary>
        /// clear all information about an item which was previously displayed
        /// </summary>
        private void clearItemInfo()
        {
            //clear all
            chkBShare.Checked = false;
            ddlCategory.ResetText();
            tbSummary.Text = "";
            tbPros.Text = "";
            tbCons.Text = "";
            tbTag.Text = "";
            mtbRating.Text = "0.0";
            tbReviewFile.Text = "";
            tbFileLocation.Text = "";
            lblFileSize.Text = "N/A";
            lblFileExistence.Text = "N/A";
            chkBCopy.Checked = false;
            
        }

        /// <summary>
        /// load all result item to the form
        /// </summary>
        private void loadResultItems()
        {
            bRefreshing = true;            
            bindDataToGridView();
            //if the list is not null
            if (arlResultList!= null && arlResultList.Count != 0)
            {
                //show the first item's information
                loadResultItemInfo((ResultItem)arlResultList[0]);
                currentSelectedItemIndex = 0;
            }
            else
            {
                loadResultItemInfo(null);
            }
           
            bRefreshing = false;
        }
        
        /// <summary>
        /// load result items to gridview
        /// </summary>
        private void bindDataToGridView()
        {
            //clear all data in the grid view
            bNeedSaveItemInfo = false;
            bNeedSaveGrdvInfo = false;
            grdvItem.Columns.Clear();

            //build the data table for gridview
            DataTable dt = new DataTable();
            //add 10 columns
            for (int i = 0; i < 11; i++)
            {
                dt.Columns.Add();
            }

            int iCount = 1;
            if (arlResultList != null)
            {
                //for each item, add one row
                foreach (ResultItem itemObj in arlResultList )
                {
                    ArrayList arlOfBibTexese = itemObj.ItemObj.BibTexes;

                    string[] itemArray = getItemArrayForDataRow(iCount, arlOfBibTexese,itemObj.MatchPercentage);
                    dt.Rows.Add(itemArray);
                    //next row
                    iCount++;
                }
            }
            
            grdvItem.DataSource = dt;
            setReadOnlyToNetworkItems();
            customizeGridView();
        }

        /// <summary>
        /// set rows which display Network Item to read only, the rest are set to editable
        /// </summary>
        private void setReadOnlyToNetworkItems()
        {
            if (grdvItem.Rows.Count != 0)
            {
                for (int i = 0; i < grdvItem.Rows.Count; i++)
                {
                    if (((ResultItem)arlResultList[i]).SourceOfItem == ResultItem.ITEM_SOURCE_NETWORK)
                    {
                        grdvItem.Rows[i].ReadOnly = true;
                    }
                    else
                        grdvItem.Rows[i].ReadOnly = false;
                }
            }
        }

        /// <summary>
        /// prepare data for construct data table which then used to generate gridview
        /// </summary>
        /// <param name="iCount"></param>
        /// <param name="arlOfBibTexese"></param>
        /// <param name="matchPercentage"></param>
        /// <returns></returns>
        private string[] getItemArrayForDataRow(int iCount, ArrayList arlOfBibTexese, double matchPercentage)
        {
            //itemArray describe the data row in the gridview
            string[] itemArray = new string[11];
            for (int i = 0; i < 11; i++)
            {
                itemArray[i] = "";
            }
            //first value is index number
            itemArray[0] = iCount.ToString();
            itemArray[1] = matchPercentage.ToString();

            foreach (Object btStruct in arlOfBibTexese)
            {

                BibTexStruct bts = (BibTexStruct)btStruct;
                switch (bts.name)
                {
                    case "title":
                        itemArray[2] = bts.value; break;
                    case "author":
                        itemArray[3] = bts.value; break;
                    case "publisher":
                        itemArray[4] = bts.value; break;
                    case "year":
                        itemArray[5] = bts.value; break;
                    case "edition":
                        itemArray[6] = bts.value; break;
                    case "pages":
                        itemArray[7] = bts.value; break;
                    case "editor":
                        itemArray[8] = bts.value; break;
                    case "organization":
                        itemArray[9] = bts.value; break;
                    case "volume":
                        itemArray[10] = bts.value; break;
                }
            }
            return itemArray;
        }

        /// <summary>
        /// customize the gridview, column by column
        /// </summary>
        private void customizeGridView()
        {
            for (int i = 0; i < 11; i++)
            {
                switch (i)
                {
                    case 0: grdvItem.Columns[0].HeaderText = "Index"; grdvItem.Columns[0].ReadOnly = true; grdvItem.Columns[0].Width = 50; break;
                    case 1: grdvItem.Columns[1].HeaderText = "Match (%)"; grdvItem.Columns[1].ReadOnly = true; grdvItem.Columns[1].Width = 60; break;
                    case 2: grdvItem.Columns[2].HeaderText = "Title"; grdvItem.Columns[2].Width = 200; break;
                    case 3: grdvItem.Columns[3].HeaderText = "Author"; grdvItem.Columns[3].Width = 150; break;
                    case 4: grdvItem.Columns[4].HeaderText = "Publisher"; grdvItem.Columns[4].Width = 100; break;
                    case 5: grdvItem.Columns[5].HeaderText = "Year"; grdvItem.Columns[5].Width = 50; break;
                    case 6: grdvItem.Columns[6].HeaderText = "Edition"; grdvItem.Columns[6].Width = 50; break;
                    case 7: grdvItem.Columns[7].HeaderText = "Pages"; grdvItem.Columns[7].Width = 50; break;
                    case 8: grdvItem.Columns[8].HeaderText = "Editor"; grdvItem.Columns[8].Width = 100; break;
                    case 9: grdvItem.Columns[9].HeaderText = "Organization"; grdvItem.Columns[9].Width = 100; break;
                    case 10: grdvItem.Columns[10].HeaderText = "Volume"; grdvItem.Columns[10].Width = 50; break;

                }

            }
        }

        
        /// <summary>
        /// reload the form
        /// </summary>
        internal void reload()
        {
            load();
        }

        /// <summary>
        /// close the form
        /// </summary>
        private void formClose()
        {
            if (bNeedSaveGrdvInfo || bNeedSaveItemInfo)
            {
                int returnValue = Common.Global.showMsgThreeButtons("You've made some changes, Do you want to save information before close?", 'I');
                if (returnValue == 1)
                {
                    if (bNeedSaveItemInfo) saveItemInfo();
                    if (bNeedSaveGrdvInfo) saveGrdvInfo();
                }
                else if (returnValue == -1)   //btn Cancel is clicked -> no action to be taken        
                    return;
            }
            this.Close(); //close the library form    
        }

        #endregion

        #region "event handlers"

        /// <summary>
        /// close the form
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lblCLose_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            this.Close();            
        }

        /// <summary>
        /// tags have been changed
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tbTag_TextChanged(object sender, EventArgs e)
        {
            if (!rowSelectionChanged && !bRefreshing)
                bNeedSaveItemInfo = true;
        }

        private void ddlCategory_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!rowSelectionChanged && !bRefreshing)
                bNeedSaveItemInfo = true;
        }

        /// <summary>
        /// button update (or copy the file for the not-on-local items) is clicked
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnUpdateInfo_Click(object sender, EventArgs e)
        {
            //if no item is selected, do nothing
            if (grdvItem.Rows.Count == 0)
                return;

            //otherwise,
            int itemIndex = grdvItem.SelectedRows[0].Index;
            if (((ResultItem)arlResultList[itemIndex]).SourceOfItem == ResultItem.ITEM_SOURCE_NETWORK)
            {
                //means to copy to local library

                //to do here
                copyToLocal((ResultItem)arlResultList[itemIndex]);

            }
                //if the resource is on the local -> it mean to update the information.
            else if (bNeedSaveItemInfo)
            {
                saveItemInfo();
                Common.Global.showMsgOneButton("Changes have been saved successfully", 'I');
            }
            else
                Common.Global.showMsgOneButton("No changes have been made to this item. Item is up to date", 'I');
        }
        
        /// <summary>
        /// happens when summary of item's comment has been changed
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tbSummary_TextChanged(object sender, EventArgs e)
        {
            if (!rowSelectionChanged && !bRefreshing)
                bNeedSaveItemInfo  = true;
        }

        /// <summary>
        /// happens when pros of item's comment has been changed
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tbPros_TextChanged(object sender, EventArgs e)
        {
            if (!rowSelectionChanged && !bRefreshing)
                bNeedSaveItemInfo = true;
        }


        /// <summary>
        /// happens when cons of item's comment has been changed
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tbCons_TextChanged(object sender, EventArgs e)
        {
            if (!rowSelectionChanged && !bRefreshing)
                bNeedSaveItemInfo = true;
        }

        /// <summary>
        /// happens when location of the file has been changed
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tbFileLocation_TextChanged(object sender, EventArgs e)
        {
            if (!rowSelectionChanged && !bRefreshing)
                bNeedSaveItemInfo = true;
        }

        /// <summary>
        /// happens when use decide to copy (to update) the file to local libray folder
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void chkBCopy_CheckedChanged(object sender, EventArgs e)
        {
            if (!rowSelectionChanged && !bRefreshing)
                bNeedSaveItemInfo = true;
        }

        /// <summary>
        /// happens when user decide to share or not share the item
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void chkBShare_CheckedChanged(object sender, EventArgs e)
        {
            if (!rowSelectionChanged && !bRefreshing)
                bNeedSaveItemInfo = true;
        }
        
        /// <summary>
        /// happens when user's rating of the item has been changed
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void mtbRating_TextChanged(object sender, EventArgs e)
        {
            if (!mtbRating.Text.Equals(" .") && Double.Parse(mtbRating.Text) > 5)
            {
                Common.Global.showMsgOneButton("Invalid value! Rating must be in between 0 and 5", 'W');
                mtbRating.Text = ((ResultItem)(ArlResultList[currentSelectedItemIndex])).CommentObj.Rating.ToString();
            }
            if (!rowSelectionChanged && !bRefreshing)
                bNeedSaveItemInfo = true;
        }

        /// <summary>
        /// happens when user would like to delete the item
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDelete_Click(object sender, EventArgs e)
        {
            //check if the gridview doesn't contain any item,if so do nothing
            if (grdvItem.SelectedRows.Count != 0)
            {
                //check application's setting, if need to ask before delete
                if ((new AppSetting()).Lib_AskBeforeDelete)
                {
                    int answer = Common.Global.showMsgTwoButtons("Delete the selected item", Common.GUI.MsgBoxTwoButtons.YES_NO, 'W');
                    if (answer == 1)
                        deleteItem();
                    else
                        return;
                }
                else
                    deleteItem();
            }
        }

        /// <summary>
        /// re-search with the same criteria and display new result
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lnkBtnRefresh_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {            
            
        }


        /// <summary>
        /// happens when user would like to make a new search
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lnkBtnNewSearch_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            bool alreadyExist = false;
            foreach (Form frm in (this.MdiParent.MdiChildren))
            {
                frm.WindowState = FormWindowState.Normal;
                if (frm.GetType().Equals(typeof(Pbdms.Forms.Tools.FrmSearch)))
                {
                    frm.Activate();
                    ((Pbdms.Forms.Tools.FrmSearch)frm).clearSearchCriteria();
                    alreadyExist = true;
                    break;
                }
            }
            if (!alreadyExist)
            {
                Pbdms.Forms.Tools.FrmSearch frmSerach = new Pbdms.Forms.Tools.FrmSearch();
                frmSerach.MdiParent = this.MdiParent;
                frmSerach.clearSearchCriteria();
                frmSerach.Show();
            }
        }

        /// <summary>
        /// happens when user press the button to browse file
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnBrowseFile_Click(object sender, EventArgs e)
        {
            this.openFileDlg.ShowDialog();
            openFileDlg.Multiselect = false;

        }

        /// <summary>
        /// happens when return from browsing file with a file is selected
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void openFileDlg_FileOk(object sender, CancelEventArgs e)
        {
            chkBCopy.Enabled = true;
            tbFileLocation.Text = openFileDlg.FileName;
            //file location is changed -> need to ask to save before exiting the window
            bNeedSaveItemInfo  = true;
        }
        private void openFileDlgReviewFile_FileOk(object sender, CancelEventArgs e)
        {
            tbReviewFile.Text = openFileDlgReviewFile.FileName;
            //file location is changed -> need to ask to save before exiting the window
            bNeedSaveItemInfo = true;
        }
        /// <summary>
        /// happens when value or content of the cell in the gridview has been changed
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void grdvItem_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            int selectedIndex = grdvItem.SelectedRows[0].Index;
            if (((ResultItem)arlResultList[selectedIndex]).SourceOfItem == ResultItem.ITEM_SOURCE_NETWORK)
            {
                //item is on the network, not on local, no need to save changes
            }
            else
            {
                if (!bRefreshing)
                    bNeedSaveGrdvInfo = true;
            }
        }

        ///// <summary>
        ///// happens when user press the link button to view seting for this form
        ///// </summary>
        ///// <param name="sender"></param>
        ///// <param name="e"></param>
        //private void lnkBtnSetting_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        //{
        //    bool alreadyExist = false;
        //    this.WindowState = FormWindowState.Normal;
        //    foreach (Form frm in (this.MdiParent.MdiChildren))
        //    {
        //        if (frm.GetType().Equals(typeof(Pbdms.Forms.Application.FrmPreference)))
        //        {
        //            frm.WindowState = FormWindowState.Normal;
        //            frm.Activate();
        //            ((TabControl)(frm.Controls.Find("tabCtrl", true)[0])).SelectedIndex = 2;
        //            alreadyExist = true;
        //            break;
        //        }
        //    }
        //    if (!alreadyExist)
        //    {
        //        Pbdms.Forms.Application.FrmPreference frmPreference = new Pbdms.Forms.Application.FrmPreference();
        //        frmPreference.MdiParent = this.MdiParent;
        //        frmPreference.WindowState = FormWindowState.Normal;
        //        ((TabControl)(frmPreference.Controls.Find("tabCtrl", true)[0])).SelectedIndex = 2;
        //        frmPreference.Show();
        //    }
        //}

        /// <summary>
        /// close the form
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lnkBtnClose_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {            
            formClose();
        }

        #endregion

        #region "delete, update information"

        /// <summary>
        /// save information of the item
        /// </summary>
        private void saveItemInfo()
        {
            if (grdvItem.SelectedRows.Count != 0)
            {
                int selectedObjectIndex = int.Parse(grdvItem.SelectedRows[0].Cells[0].Value.ToString()) - 1;
                Item itemObj = ((ResultItem)arlResultList[selectedObjectIndex]).ItemObj;

                itemObj.Category = ddlCategory.SelectedItem.ToString();
                ItemController.create().updateItemToDB(itemObj);

                itemObj.BPrivate = !chkBShare.Checked;

                String itemId = itemObj.Id;
                Comment commentObj = CommentController.create().getCommentFromDB(itemId);
                FileInfo fileInfoObj = FileInfoController.create().getFileInfoObject(itemId);

                //start overwriting
                commentObj.Summary = tbSummary.Text;
                commentObj.Pros = tbPros.Text;
                commentObj.Cons = tbCons.Text;

                if (mtbRating.Text.Equals(" ."))
                    commentObj.Rating =0.0;
                else
                    commentObj.Rating = Double.Parse(mtbRating.Text);

                if (!commentObj.ReviewFile.Equals(tbReviewFile.Text))
                {
                    if (System.IO.File.Exists(tbReviewFile.Text))
                    {
                        String reviewFile = tbReviewFile.Text;
                        Pbdms.AppSetting aSetting = new AppSetting();
                        try
                        {
                            Common.Global.copyFile(reviewFile, aSetting.LibFolder + "\\" + reviewFile.Substring(reviewFile.LastIndexOf("\\") + 1));
                            //delete old file
                            if (System.IO.File.Exists(commentObj.ReviewFile))
                                System.IO.File.Delete(commentObj.ReviewFile);
                            //update new file
                            commentObj.ReviewFile = aSetting.LibFolder + "\\" + reviewFile.Substring(reviewFile.LastIndexOf("\\") + 1);
                        }
                        catch
                        {
                            Common.Global.showMsgOneButton("Unexpected Error, couldn't finish copying the new review file\r\n No change of review file has been made", 'I');

                        }
                    }
                }

                String[] arrString = tbTag.Text.Split(',');
                if (arrString.Length != 0)
                {
                    commentObj.Tags = new ArrayList();
                    for (int i = 0; i < arrString.Length; i++)
                    {
                        commentObj.Tags.Add(arrString[i]);
                    }
                }

                //file information                
                String fileLocation = tbFileLocation.Text;
                if (!fileLocation.Equals(""))
                {
                    //if item's file is located on internet.
                    if (fileLocation.Contains("http"))
                    {
                        fileInfoObj.Location = fileLocation.Substring(0, fileLocation.LastIndexOf("/"));
                        fileInfoObj.FileName = fileLocation.Substring(fileLocation.LastIndexOf("/") + 1);
                        fileInfoObj.Size = 0;
                        fileInfoObj.Existence = false;
                    }
                    else  //if item's file is located on local machine.
                    {
                        if (System.IO.File.Exists(fileLocation))
                        {
                            //if the file exists, store its information
                            fileInfoObj.Existence = true;

                            System.IO.FileInfo fInfo = new System.IO.FileInfo(fileLocation);
                            fileInfoObj.Location = fInfo.Directory.FullName;
                            fileInfoObj.FileName = fInfo.Name;
                            fileInfoObj.Size = fInfo.Length;

                            //check if need to copy the file to the folder
                            if (chkBCopy.Checked)
                            {
                                Pbdms.AppSetting aSetting = new AppSetting();
                                try
                                {
                                    Common.Global.copyFile(fileLocation, aSetting.LibFolder + "\\" + fileInfoObj.FileName);
                                    tbFileLocation.Text = aSetting.LibFolder + "\\" + fileInfoObj.FileName;
                                    fileInfoObj.Size = (new System.IO.FileInfo(tbFileLocation.Text)).Length;
                                    lblFileSize.Text = fileInfoObj.Size.ToString();
                                    fileInfoObj.Location = aSetting.LibFolder;    
                                }
                                catch
                                {
                                    Common.Global.showMsgOneButton("Unexpected Error, couldn't finish copyding the file", 'I');
                                }
                            }
                        }
                    }
                }

                //update to database
                CommentController.create().updateCommentToDB(commentObj);
                if (!fileLocation.Equals("")) 
                    FileInfoController.create().updateFileInfoToDB(fileInfoObj);
                ItemController.create().updateItemToDB(itemObj);
            }        
            bNeedSaveItemInfo = false;
        }

        /// <summary>
        /// copy the file of the item from the network to local machine
        /// </summary>
        /// <param name="resultItem"></param>
        private void copyToLocal(Common.DataObject.ResultItem resultItem)
        {
            AppSetting aSetting = new AppSetting();
            FrmMain frmMain = ((FrmMain)(this.MdiParent));
            if ((resultItem.FileInfoObj.Existence == true && System.IO.File.Exists(aSetting.LibFolder + "\\" + resultItem.FileInfoObj.FileName))
                || (!resultItem.CommentObj.ReviewFile.Trim().Equals("")&& System.IO.File.Exists(aSetting.LibFolder + "\\" + resultItem.CommentObj.ReviewFile)))
            {
                int dlgResult = Common.Global.showMsgTwoButtons("Duplicate file(s) in the library!\r\nWould you like to save to seperate file(s)?\r\nSelect \"No\" to overwrite", 
                    Common.GUI.MsgBoxTwoButtons.YES_NO, 'I');
                if (dlgResult == Common.GUI.MsgBoxTwoButtons.DIALOG_RESULT_YES)
                {                   
                    //assign the name for the file
                    if (resultItem.FileInfoObj.Existence == true
                        && System.IO.File.Exists(aSetting.LibFolder + "\\" + resultItem.FileInfoObj.FileName))
                    {
                        int i = 2;
                        string tempFileName = resultItem.FileInfoObj.FileName;
                        while (System.IO.File.Exists(Common.Global.getLibFolder() + "\\" + tempFileName))
                        {
                            tempFileName = resultItem.FileInfoObj.FileName.Insert(resultItem.FileInfoObj.FileName.IndexOf("."), "_" + i.ToString());
                            i++;
                        }
                        resultItem.FileInfoObj.FileName = tempFileName;
                    }
                    //assign the name for the file
                    if (!resultItem.CommentObj.ReviewFile.Trim().Equals("") && System.IO.File.Exists(aSetting.LibFolder + "\\" + resultItem.CommentObj.ReviewFile))
                    {
                        int i = 2;
                        string tempFileName = resultItem.CommentObj.ReviewFile ;
                        while (System.IO.File.Exists(Common.Global.getLibFolder() + "\\" + tempFileName))
                        {
                            tempFileName = resultItem.CommentObj.ReviewFile.Insert(resultItem.CommentObj.ReviewFile.IndexOf("."), "_" + i.ToString());
                            i++;
                        }
                        resultItem.CommentObj.ReviewFile = tempFileName;
                    }                   
                }
            }

            Program.networkCtrller.sendDownloadRequest(resultItem.ItemObj.Id, resultItem.FileInfoObj.Location, resultItem.FileInfoObj.FileName, resultItem.CommentObj.ReviewFile);
            //pause the current thread for 1 seconds
            System.Threading.Thread.CurrentThread.Join(3000);
                        
            resultItem.FileInfoObj.Location = aSetting.LibFolder;
            resultItem.ItemObj.BPrivate = true;
            Item itemObj = resultItem.ItemObj;

            Comment commentObj = resultItem.CommentObj;
            //modify the path to the newly copied review file
            
            commentObj.ReviewFile = aSetting.LibFolder + "\\" + resultItem.CommentObj.ReviewFile.Substring(resultItem.CommentObj.ReviewFile.LastIndexOf("\\")+1);
            FileInfo fileInfoObj = resultItem.FileInfoObj;
            BusinessLogic.ItemSynchronizer.AppendNewItem(ref itemObj ,ref commentObj ,ref fileInfoObj);
            resultItem.SourceOfItem = ResultItem.ITEM_SOURCE_LOCAL;
            this.loadResultItemInfo(resultItem);


        }

        /// <summary>
        /// save changes in the gridview cells' content
        /// </summary>
        private void saveGrdvInfo()
        {
            //update all item in the gridview
            DataTable dtTable = (DataTable)grdvItem.DataSource;
            for (int i = 0; i < grdvItem.Rows.Count; i++)
            {
                int itemIndex = int.Parse(grdvItem.Rows[i].Cells[0].Value.ToString()) - 1;

                //only update the item on local computer
                if (((ResultItem)arlResultList[itemIndex]).SourceOfItem == ResultItem.ITEM_SOURCE_LOCAL)
                {
                    Item itemObj = ((ResultItem)arlResultList[itemIndex]).ItemObj;

                    itemObj.BibTexes = new ArrayList();
                    for (int j = 2; j < grdvItem.Columns.Count; j++)
                    {
                        if (!grdvItem.Rows[i].Cells[j].Value.ToString().Equals(""))
                        {
                            BibTexStruct bts = new BibTexStruct();
                            bts.name = grdvItem.Columns[j].HeaderText.ToLower();
                            bts.value = grdvItem.Rows[i].Cells[j].Value.ToString();
                            itemObj.BibTexes.Add(bts);
                        }
                    }
                    ItemController.create().updateItemToDB(itemObj);
                }
            }
            bNeedSaveGrdvInfo = false;

        }

        /// <summary>
        /// delete an item from the gridview and database (if the item is on the local machine)
        /// </summary>
        private void deleteItem()
        {
            int selectedObjectIndex = int.Parse(grdvItem.SelectedRows[0].Cells[0].Value.ToString()) - 1;
            //delete all item in , comment , fileinfo which belong to this item
            if (((ResultItem)arlResultList[selectedObjectIndex]).SourceOfItem == ResultItem.ITEM_SOURCE_LOCAL)
            {
                BusinessLogic.ItemSynchronizer.DeleteItem(((ResultItem)arlResultList[selectedObjectIndex]).ItemObj.Id);
                grdvItem.Rows.RemoveAt(selectedObjectIndex);
            }
            
            //update after remove
            arlResultList.RemoveAt(selectedObjectIndex);
            this.loadResultItems();
            //bindDataToGridView();
            if (arlResultList != null && arlResultList.Count>0)
            {
                
                if (arlResultList.Count == selectedObjectIndex)
                {
                    //delete the last item
                    grdvItem.CurrentCell = grdvItem.Rows[selectedObjectIndex - 1].Cells[1];
                    loadResultItemInfo((ResultItem)arlResultList[selectedObjectIndex - 1]);
                }
                else
                {
                    grdvItem.CurrentCell = grdvItem.Rows[selectedObjectIndex].Cells[1];
                    loadResultItemInfo((ResultItem)arlResultList[selectedObjectIndex]);
                }
            }
        }

        #endregion

        /// <summary>
        /// export list of result to PDF file
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnToPDF_Click(object sender, EventArgs e)
        {
            if (arlResultList == null || arlResultList.Count == 0)                 
            {
                Common.Global.showMsgOneButton("Failed!\r\nThere is no item in the list", 'I');
                return;
            }
            try
            {

                //save as.. (file name and path)
                String filePath = "";
                saveFileDlg.DefaultExt = ".pdf";

                DialogResult dlgResult = saveFileDlg.ShowDialog(this);
                if (dlgResult.Equals(DialogResult.Cancel))
                {
                    Common.Global.showMsgOneButton("You've cancelled the operation", 'I');
                    return;
                }
                else if (dlgResult.Equals(DialogResult.OK))
                {
                    filePath = saveFileDlg.FileName;


                    //form the arraylist
                    ArrayList arlBibTexes = new ArrayList();
                    foreach (object obj in arlResultList)
                    {
                        ResultItem itemObj = (ResultItem)obj;
                        arlBibTexes.Add(Common.Global.constructBibTex(itemObj.ItemObj.BibTexes));
                    }

                    //get PDF file
                    Pbdms.BusinessLogic.PDFReporter.PDFReporter.printArlOfBibTexes(arlBibTexes, filePath);
                    Common.Global.showMsgOneButton("A Pdf file, " + filePath + ", has been successfully created", 'I');
                }
            }
            catch { }
        }

        private void btnToTextFile_Click(object sender, EventArgs e)
        {
            if (arlResultList == null || arlResultList.Count == 0)
            {
                Common.Global.showMsgOneButton("Failed!\r\nThere is no item in the list", 'I');
                return;
            }
            try
            {
                //save as.. (file name and path)
                String filePath = "";
                saveFileDlg.DefaultExt = ".txt";

                DialogResult dlgResult = saveFileDlg.ShowDialog(this);
                if (dlgResult.Equals(DialogResult.Cancel))
                {
                    Common.Global.showMsgOneButton("You've cancelled the operation", 'I');
                    return;
                }
                else if (dlgResult.Equals(DialogResult.OK))
                {
                    filePath = saveFileDlg.FileName;
                    System.IO.StreamWriter fw = new System.IO.StreamWriter(filePath, false);
                    try
                    {
                        //write the string into the file
                        int i = 1;
                        foreach (object obj in arlResultList)
                        {
                            ResultItem itemObj = (ResultItem)obj;
                            fw.WriteLine(i++ + ". " + Common.Global.constructBibTex(itemObj.ItemObj.BibTexes));
                        }
                    }
                    catch
                    {
                        Pbdms.Common.Global.showMsgOneButton("Error while writing into the file", 'C');
                    }
                    finally
                    {
                        fw.Close();
                    }
                }
            }
            catch { }
        }

        private void btnPrintPdfThis_Click(object sender, EventArgs e)
        {
            if (arlResultList == null || arlResultList.Count == 0)
            {
                Common.Global.showMsgOneButton("Failed!\r\nThere is no item in the list", 'I');
                return;
            }
            try
            {

                //save as.. (file name and path)
                String filePath = "";
                saveFileDlg.DefaultExt = ".pdf";

                DialogResult dlgResult = saveFileDlg.ShowDialog(this);
                if (dlgResult.Equals(DialogResult.Cancel))
                {
                    Common.Global.showMsgOneButton("You've cancelled the operation", 'I');
                    return;
                }
                else if (dlgResult.Equals(DialogResult.OK))
                {
                    filePath = saveFileDlg.FileName;
                    //currently selected item
                    StringBuilder sb = new StringBuilder();
                    int selectedIndex = int.Parse(grdvItem.SelectedRows[0].Cells[0].Value.ToString())-1;
                    ResultItem resultItemObj = (ResultItem)arlResultList[selectedIndex];

                    string itemBibText = Common.Global.constructBibTex(resultItemObj.ItemObj.BibTexes);
                    sb.Append(itemBibText);
                    sb.Append("\r\nCategory: " + resultItemObj.ItemObj.Category);
                    if (resultItemObj.FileInfoObj.Existence)
                        sb.Append("\r\nHas File: Yes");
                    else
                        sb.Append("\r\nHas File: No");                    
                    sb.Append("\r\nFile Size: " + resultItemObj.FileInfoObj.Size.ToString());
                    if (resultItemObj.ItemObj.BPrivate)
                        sb.Append("\r\nShared on the network: Yes" );
                    else
                        sb.Append("\r\nShared on the network: No");
                    if (resultItemObj.CommentObj.Tags!=null && resultItemObj.CommentObj.Tags.Count > 0)
                    {
                        sb.Append("\r\nTag: ");
                        int j = 0;
                        foreach (string strTag in resultItemObj.CommentObj.Tags)
                        {
                            if (j>0)
                                sb.Append(", ");
                            sb.Append(strTag);
                            j++;
                        }          
                    }
                    sb.Append("\r\nRating: " + resultItemObj.CommentObj.Rating.ToString());                    
                    sb.Append("\r\nSummary: " + resultItemObj.CommentObj.Summary);
                    sb.Append("\r\nPros: " + resultItemObj.CommentObj.Pros);
                    sb.Append("\r\nCons: " + resultItemObj.CommentObj.Cons);
                    if (resultItemObj.CommentObj.ReviewFile.Equals(""))
                        sb.Append("\r\nReview File: N/A");
                    else
                        sb.Append("\r\nReview File: " + resultItemObj.CommentObj.ReviewFile);

                    //get PDF file
                    Pbdms.BusinessLogic.PDFReporter.PDFReporter.printString(sb.ToString(), filePath);
                    Common.Global.showMsgOneButton("A Pdf file, " + filePath + ", has been successfully created", 'I');
                }
            }
            catch { }
        }

        private void btnReviewFileBrowser_Click(object sender, EventArgs e)
        {
            this.openFileDlgReviewFile.ShowDialog();
            openFileDlg.Multiselect = false;
        }

        private void btnOpenFile_Click(object sender, EventArgs e)
        {
            if (!tbReviewFile.Equals(""))
            {
                try
                {

                    System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(tbReviewFile.Text);
                    psi.UseShellExecute = true;
                    System.Diagnostics.Process.Start(psi);
                }
                catch
                {
                    Common.Global.showMsgOneButton("Unable to open the file, please check the file path",'C');
                }
            }

        }

        private void btnRunFileDoc_Click(object sender, EventArgs e)
        {
            if (!tbFileLocation.Text.Equals(""))
            {
                try
                {

                    System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(tbFileLocation.Text);
                    psi.UseShellExecute = true;
                    System.Diagnostics.Process.Start(psi);
                }
                catch
                {
                    Common.Global.showMsgOneButton("Unable to open the file, please check the file path", 'C');
                }
            }
        }

        private void btnSaveChanges_Click(object sender, EventArgs e)
        {
            if (bNeedSaveGrdvInfo || bNeedSaveItemInfo)
            {
                if (bNeedSaveGrdvInfo) saveGrdvInfo();
                if (bNeedSaveItemInfo) saveItemInfo();
                Common.Global.showMsgOneButton("Changes have been successfully updated", 'I');
            }
            else
            {
                Common.Global.showMsgOneButton("No changes have been made so far", 'I');
            }
        }

        private void btnAddBuddy_Click(object sender, EventArgs e)
        {

            if (ddlCompBuddy.Items.Count >= 1 && ddlCompBuddy.SelectedIndex >= 0)
            {
                int i = ddlCompBuddy.SelectedIndex;
                String str = (String)(arlCompBuddies[i]);
                String strName = str.Substring(0, str.LastIndexOf("(")).Trim();
                String strIP = str.Trim().Substring(str.LastIndexOf("(") + 1);
                strIP = strIP.Trim().Substring(0, strIP.Length - 1);
                BuddyController.create().appendBuddyToDB(strName, strIP);
                Common.Global.showMsgOneButton("The buddy has been added successfully!", 'I');
            }
            else
            {
                Common.Global.showMsgOneButton("No buddy is added!", 'I');
            }
        }

        private void btnGoIP_Click(object sender, EventArgs e)
        {
            if (Global.isAnIPAddress(tbIP.Text.Trim()))
            {
                arlResultList = new ArrayList();
                arlCompBuddies = new ArrayList();
                ntwCtrl.sendBrowseRequest(tbIP.Text,processReceivedSearchResult,processBrowseResultBuddyReceived);
                loadResultItems();
                loadCompBuddies();
            }
            else
            {
                Global.showMsgOneButton("The text is not a valid IP Address!", 'W');
            }
        }

        public void processReceivedSearchResult(object o1, Pbdms.NetworkDealer.EventArgs.SearchResultReceivedEventArgs e)
        {
            System.Collections.ArrayList arl = e.ArlOfResultItems;
            
            foreach (object obj in arl)
            {
                arlResultList.Add(obj);
            }
        }
        public void processBrowseResultBuddyReceived(object sender, Pbdms.NetworkDealer.EventArgs.BrowseResultBuddyReceivedEventArgs e)
        {
            String[] strBuddies = e.strBuddies.Split('*');
            
            for (int i = 0; i<strBuddies.Length; i++)
            {
                arlCompBuddies.Add(strBuddies[i].Trim());
            }

        }

        private void btnGoName_Click(object sender, EventArgs e)
        {
            if (ddlBuddyName.Items.Count > 0 && ddlBuddyName.SelectedIndex != -1)
            {
                this.Cursor = Cursors.WaitCursor;
                Buddy bdy = (Buddy)(arlMyBuddies[ddlBuddyName.SelectedIndex]);
                arlResultList = new ArrayList();
                arlCompBuddies = new ArrayList();
                ntwCtrl.sendBrowseRequest(bdy.IpAdd, processReceivedSearchResult, processBrowseResultBuddyReceived);
                loadResultItems();
                loadCompBuddies();
                this.Cursor = Cursors.Default;
            }
            else
            {
                Common.Global.showMsgOneButton("Please specify a valid target buddy", 'W');
            }
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            if (ddlCompBuddy.Items.Count > 0 && ddlCompBuddy.SelectedIndex != -1)
            {
                this.Cursor = Cursors.WaitCursor;
                Buddy bdy = (Buddy)(arlMyBuddies[ddlCompBuddy.SelectedIndex]);
                arlResultList = new ArrayList();
                arlCompBuddies = new ArrayList();
                ntwCtrl.sendBrowseRequest(bdy.IpAdd, processReceivedSearchResult, processBrowseResultBuddyReceived);
                loadResultItems();
                loadCompBuddies();
                this.Cursor = Cursors.Default;                 
            }
            else
            {
                Common.Global.showMsgOneButton("Please specify a valid target buddy", 'W');
            }
        }
        
    }
}